package org.weed.gadgets.audio.asf;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.weed.gadgets.util.NioFileReader;

public class ASFHeaderObject extends ASFObject {
	protected static final int HEADER_SIZE = 30;
	protected final int headerObjectCount;
	protected List<ASFObject> subObjects;
	public ASFHeaderObject(GUID guid, long size, long startIndex, int headerObjectCount, int headerSize) {
		super(guid, size, startIndex, headerSize);
		this.headerObjectCount = headerObjectCount;
		subObjects = new ArrayList<ASFObject>();
	}
	
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append(super.toString()).append("\n")
				.append("SubObject Count: ").append(headerObjectCount);
		return builder.toString();
	}
	
	public static ASFHeaderObject getASFHeaderObject(NioFileReader reader) {
		ASFObject obj = getASFObject(reader, 0);
		BigInteger number = new BigInteger(1, reader.reverseRead(24, ASFConstants.DWORD));
		int headerObjectCount = number.intValue();
		return new ASFHeaderObject(obj.guid, obj.size, obj.index, headerObjectCount, HEADER_SIZE);
	}
	
	@Override
	public ASFObject loadData(NioFileReader reader) {
		long index = dataIndex;
		for (int i=0; i<headerObjectCount; i++) {
			ASFObject subObj = ASFObject.getASFObject(reader, index);
			subObj.loadData(reader);
			index += subObj.size;
			subObjects.add(subObj);
		}
		return this;
	}
	
	public static void main(String[] args) throws Exception {
		NioFileReader reader = new NioFileReader("C:\\Users\\ctang\\Desktop\\test.wma");
		ASFHeaderObject header = ASFHeaderObject.getASFHeaderObject(reader);
		header.loadData(reader);
		System.out.println(header);
		long total = header.size;
		for (int i=0; i<header.headerObjectCount;i++) {
			System.out.println("==============");
			ASFObject obj = header.subObjects.get(i);
			total -= obj.size;
			System.out.println(obj);
		}
		System.err.println(total);
	}
}
